import React from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import styles from '@/pages/DataStatistics/AnswerDetailStatis/index.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Card, Col, Form, Row, DatePicker, Select, Button, Table, Pagination } from 'antd';
import moment from 'moment';
import { doRobotList } from '@/services/robotManagement';
import { exportDialogStatistics, fetchDialogStatistics } from '@/services/datastatistics';
import UserSession from '@/UserSession';

class DialogStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      robotList: [],
      list: [],
      loading: true,
      total: 0,
      queryData: {
        current: 1,
        size: 10,
        applicationId: '0',
        fromDate: moment().subtract('7', 'days').format('YYYY-MM-DD'),
        toDate: moment().format('YYYY-MM-DD')
      }
    }
  }

  componentDidMount() {
    this.getRobot();
    this.getList();
  }

  /**
   * 获取所有机器人（作为筛选条件）
   */
  getRobot = async () => {
    const res = await doRobotList({ current: 1, size: 999999 });
    this.setState({ robotList: res });
  }

  /**
   * 获取列表
   * @returns {*}
   */
  getList = () => {
    this.setState({ loading: true }, async () => {
      const { queryData } = this.state;
      const currentUser = UserSession.getCurrentUser()
      if(currentUser.applicationId){
        queryData.applicationId = currentUser.applicationId
      }
      const res = await fetchDialogStatistics(queryData);
      this.setState({ loading: false, total: res.total, list: res.records });
    })
  }

  /**
   * 查询条件
   * @returns {*}
   */
  queryByConditions = () => {
    const { form } = this.props;
    const info = form.getFieldsValue();
    console.log(info);
    this.setState({
      queryData: {
        current: 1,
        size: 10,
        applicationId: info.applicationId,
        fromDate: info.time[0].format('YYYY-MM-DD'),
        toDate: info.time[1].format('YYYY-MM-DD')
      }
    }, () => this.getList())
  }

  /**
   * 分页
   * @returns {*}
   */
  queryByPage = (page, pageSize) => {
    let { queryData } = this.state;
    queryData.current = page;
    queryData.size = pageSize;
    this.setState({ queryData }, () => this.getList());
  }

  /**
   * 导出
   * @returns {*}
   */
  exportTable = async () => {
    let { queryData } = this.state;
    const res = await exportDialogStatistics({ applicationId: queryData.applicationId, fromDate: queryData.fromDate, toDate: queryData.toDate });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { robotList, list, loading, total, queryData } = this.state;
    const columns = [
      {
        title: formatMessage({ id: 'DialogStatistics.multiTurnDialog' }),
        dataIndex: 'name',
        width: 200
      },
      {
        title: formatMessage({ id: 'DialogStatistics.category' }),
        dataIndex: 'categoryName',
        width: 200
      },
      {
        title: formatMessage({ id: 'DialogStatistics.triggerCount' }),
        dataIndex: 'hit',
        width: 100,
        align: 'center'
      },
      {
        title: formatMessage({ id: 'DialogStatistics.dialogCompletionCount' }),
        dataIndex: 'finished',
        width: 120,
        align: 'center'
      },
      {
        title: formatMessage({ id: 'DialogStatistics.completionRate' }),
        dataIndex: 'ratio',
        width: 80,
        align: 'center'
      },
      {
        title: formatMessage({ id: 'DialogStatistics.totalQACount' }),
        dataIndex: 'total',
        width: 120,
        align: 'center'
      },
      {
        title: formatMessage({ id: 'DialogStatistics.averageQACount' }),
        dataIndex: 'average',
        width: 120,
        align: 'center'
      }
    ];
    const currentUser = UserSession.getCurrentUser()

    return (
      <div style={{ height: '100%' }}>
        <PageHeaderWrapper>
          <Card style={{ height: '100%' }}>
            <Form layout={'inline'}>
              {
                currentUser.applicationId ? null : (
                    <Form.Item>
                      {getFieldDecorator('applicationId', { initialValue: '0' })(
                          <Select style={{ width: 200 }} placeholder={formatMessage({ id: 'DialogStatistics.selectApplication' })}>
                            <Select.Option value={'0'}>{formatMessage({ id: 'DialogStatistics.allApplications' })}</Select.Option>
                            {robotList.map(item => {
                              return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                            })}
                          </Select>
                      )}
                    </Form.Item>
                )
              }
              <Form.Item style={{ textAlign: 'center' }}>
                {getFieldDecorator('time', {
                  initialValue: [moment().subtract('7', 'days'), moment()]
                })(<DatePicker.RangePicker allowClear={false} style={{ width: '250px' }} />)}
              </Form.Item>
              <Form.Item>
                <Button type={'primary'} onClick={this.queryByConditions}>{formatMessage({ id: 'DialogStatistics.query' })}</Button>
              </Form.Item>
              <span style={{ float: 'right' }}>
                <Form.Item style={{ margin: 0 }}>
                  <Button onClick={this.exportTable}>{formatMessage({ id: 'DialogStatistics.export' })}</Button>
                </Form.Item>
              </span>
            </Form>
            <Row style={{ marginTop: 20 }}>
              <Col span={24}>
                <Table
                  rowKey={'id'}
                  columns={columns}
                  dataSource={list}
                  loading={loading}
                  pagination={false}
                  scroll={{ x: "auto" }}
                />
                {total > 10 ? (
                  <Pagination
                    style={{ textAlign: 'right', marginTop: 16 }}
                    total={total}
                    current={queryData.current}
                    onChange={this.queryByPage}
                    showSizeChanger={true}
                    onShowSizeChange={this.queryByPage}
                  />
                ) : null}
              </Col>
            </Row>
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default Form.create()(DialogStatistics)
